package com.zoo.controller;

import com.axq.common.cache.AuthCache;
import com.axq.common.security.utils.JwtUtils;
import com.axq.common.usermanager.login.dto.UserDto;
import com.zoo.service.LoginServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


/**
 * 登录（测试流程发起，需要先登录）
 */
@RestController
@RequestMapping(value = "/api/")
public class LoginController {

    @Autowired
    private LoginServer loginServer;

    @Autowired
    private AuthenticationManager authenticationManager;

    @GetMapping("/loginext")
    public Object loginext(UserDto userDto) {
        return loginServer.login(userDto);
    }

    /**
     * 用户登录获取token
     * @param userDto
     * @return
     */
    @GetMapping("/login")
    public String login(final UserDto userDto) {
        //todo mock 角色
        List<SimpleGrantedAuthority> roleList = new ArrayList<>();
        //todo 角色以ROLE_开头
        roleList.add(new SimpleGrantedAuthority("ROLE_OWEN"));
        Authentication authenticate =
                authenticationManager.authenticate(
                        new UsernamePasswordAuthenticationToken(userDto.getAccount(),
                                userDto.getPassword(), roleList));
        AuthCache.putVlaue(authenticate.getPrincipal().toString(), authenticate);
        return "Bearer "+ JwtUtils.createJwt(authenticate.getPrincipal().toString());
    }

}
